--[[
@classmod Input
The Input handler uses modes. Every mode has a keytable, and 
is initialized by passing a table of the form:
	{ ModeA = {{ 'type:val:press', function () [...] end } , 
				[...]}
	},
	
	[...]
	
@see MapEditor
]]

local lume = require (LIB_PATH.."lume")

return pl.class {
	_name = "Input",
	_init = function (self, modes_table)
		self.modes_table = modes_table
		self.current_mode = self:get_mode (1)
		self.pressed_key = nil
		self.pressed_mouse = nil
		self.ti_pressed_key = nil
	end,
	
	get_mode = function (self, id)
		return lume.keys(self.modes_table)[id]
	end,
	
	press_key = function (self, k)
		local k = k
		self.pressed_key = k
	end,
	
	ti_press_key = function (self, k)
		local k = k
		self.ti_pressed_key = k
	end,
	
	press_mouse = function (self, b)
		self.pressed_mouse = b
	end,
	
	get_mode_keys_table = function (self, mode)
		local mode = mode or self.current_mode
		return self.modes_table[mode]
	end,
	
	get_key_info = function (self, key_str)
		return string.match(key_str, "(%w+):(%w*):(%w*)")
	end,
	
	handle_key = function (self, key_type, value, press, func)
		if key_type == "mouse" then
			if press == "pressed" then
				if self.pressed_mouse == value then func() end
			elseif press == "down" then
				if _lm.isDown(value) then func() end
			end
		elseif key_type == "key" then
			if press == "pressed" then
				if self.pressed_key == value then func() end
			elseif press == "down" then
				if _lk.isDown(value) then func() end
			end
		elseif key_type == "text" then
			if self.ti_pressed_key then
				func(self.ti_pressed_key)
			end
		end
	end,
	
	switch_mode = function (self, mode)
		if not mode then return end
		assert(self.modes_table[mode], "input: mode not found: " .. mode)
		self.current_mode = mode
		self.pressed_key = nil
		self.pressed_mouse = nil
		self.ti_pressed_key = nil
	end,
	
	update = function (self)
		local controls = self:get_mode_keys_table ()
		lume.each(controls, function (tbl)
			local k_type, k_value, k_press = self:get_key_info (tbl[1])
			self:handle_key (k_type, k_value, k_press, tbl[2])
		end)
		self.pressed_key = nil
		self.pressed_mouse = nil
		self.ti_pressed_key = nil
	end,

}
